//
//  MDSplashScreenView.swift
//  MDPreviewImageTest
//
//  Created by Alan on 2018/1/9.
//  Copyright © 2018年 MD. All rights reserved.
//

import UIKit
import AVKit

public enum MDSplashScreenType : Int {
    case localImage //为本地图片
    case localGif  //为本地动态图
    case localVidio //为本地视频
    case netImage   //为网络图片
    case netGif   //为网络动态图
    case netVidio  //为网络视频
}


public let ToAdVC = "toAdVC"

open class MDSplashScreenView: UIView {
    open var showTime:Int = 3 //跳过按钮显示时间 为0时 不显示读秒手动跳过
    open var img:String? // 图片
    open var linkUrl:String? // 跳转链接
    open var imageValidTime:String? // 有效时间
    open var videoCycleOnce:Bool = false // 仅在视频播放时使用，默认为flase
    
    
    fileprivate var adImageView:UIImageView = {
        let adImageView = UIImageView.init(frame: UIScreen.main.bounds)
        adImageView.isUserInteractionEnabled = true
        adImageView.contentMode = .scaleAspectFill
        adImageView.clipsToBounds = true
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(MDSplashScreenView.toAdVC))
        adImageView.addGestureRecognizer(tap)
        return adImageView
    }()
    fileprivate var countButton:UIButton = {
        let countButton = UIButton(type: .custom)
        countButton.frame = CGRect(x: UIScreen.main.bounds.size.width - 84, y: 30, width: 60, height: 30)
        countButton.addTarget(self, action: #selector(MDSplashScreenView.dismiss), for: .touchUpInside)
        countButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        countButton.setTitleColor(.white, for: .normal)
        countButton.backgroundColor = UIColor.init(red: 38/255, green: 38/255, blue: 38/255, alpha: 0.6)
        countButton.layer.cornerRadius = 4
        return countButton
    }()
    
    fileprivate lazy var videoPlayer:AVPlayerViewController? = {
        let videoPlayer = AVPlayerViewController()
        videoPlayer.showsPlaybackControls = false
        videoPlayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        videoPlayer.view.frame = UIScreen.main.bounds
        videoPlayer.view.backgroundColor = .clear
        NotificationCenter.default.addObserver(self, selector: #selector(MDSplashScreenView.runLoopTheMovie(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
        return videoPlayer
    }()
    
    fileprivate lazy var countTimer:Timer?  = {
        let countTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(MDSplashScreenView.countDown), userInfo: nil, repeats: true)
        return countTimer
    }()
    
    fileprivate var count:Int = 0
    
    fileprivate var type:MDSplashScreenType?
    
   
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    public init(type:MDSplashScreenType) {
        super.init(frame: UIScreen.main.bounds)
        self.type = type
        if type != .localVidio && type != .netVidio{
            self.addSubview(adImageView)
        }else{
            self.addSubview((self.videoPlayer?.view)!)
        }
        self.addSubview(countButton)
    }

    
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func toAdVC(){
        //点击广告图时，广告图消失，同时像首页发送通知，并把广告页对应的地址传给首页
        self.dismiss()
        NotificationCenter.default.post(name: NSNotification.Name.init(ToAdVC), object: linkUrl, userInfo: nil)
    }
    
    @objc func runLoopTheMovie(_ notification:Notification){
        if videoCycleOnce{
            let playerItem = notification.object as!AVPlayerItem
            playerItem.seek(to: kCMTimeZero)
            self.videoPlayer?.player?.play()
        }else{
            dismiss()
        }
    }
    
    @objc func dismiss(){
        if videoPlayer != nil{
            videoPlayer?.player?.pause()
            videoPlayer?.view.removeFromSuperview()
            videoPlayer = nil
        }
        
        if countTimer != nil{
            countTimer?.invalidate()
            countTimer = nil
        }

        UIView.animate(withDuration: 0.5, animations: {
            self.alpha = 0.0
        }) { (finished) in
            self.removeFromSuperview()
        }
    }
    
    @objc func countDown(){
        count = count - 1
        countButton.setTitle("跳过\(count)", for: .normal)
        if count == 0{
            self.dismiss()
        }
    }
    
    
    open func showSplashScreenWithTime(showTime:Int){
        if type == .localImage{
            self.adImageView.image = UIImage.init(named: img!)
        }else if type == .localGif{
            self.adImageView.loadGif(name: img!)
        }else if type == .netImage{
            self.adImageView.image = UIImage.init(contentsOfFile: self.img!)
        }else if type == .netGif{
            let data = try? Data.init(contentsOf: URL.init(fileURLWithPath: self.img!))
            if data == nil{
                self.dismiss()
            }else{
                self.adImageView.image = UIImage.gif(data: data!)
            }
        }else if type == .localVidio{
            let filePath = Bundle.main.path(forResource: img!, ofType: "mp4")
            let videoURL = URL(fileURLWithPath: filePath!)
            let playerItem = AVPlayerItem.init(url: videoURL)
            self.videoPlayer?.player = AVPlayer.init(playerItem: playerItem)
            self.videoPlayer?.player?.play()
        }else if type == .netVidio{
            let videoURL = URL(fileURLWithPath:  img!)
            let playerItem = AVPlayerItem.init(url: videoURL)
            self.videoPlayer?.player = AVPlayer.init(playerItem: playerItem)
            self.videoPlayer?.player?.play()
        }
    
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM/dd/yyyy HH:mm"
        dateFormatter.string(from: Date())

        let  timeStampString = self.imageValidTime
        if timeStampString == nil{
            print("结束时间存储失败")
            self.dismiss()
        }
        let validTimeDate = dateFormatter.date(from: timeStampString!)

        var result:ComparisonResult?
        result = validTimeDate?.compare(Date())
        //将存下来的日期和当前日期相比，如果当前日期小于存下来的时间，则可以显示广告页，反之则不显示
        if result == .orderedAscending{
            dismiss()
        }else{
            if showTime != 0{
                self.showTime = showTime
                countButton.setTitle("跳过\(showTime)", for: .normal)
                startTimer()
            }else{
                countButton.setTitle("跳过", for: .normal)
            }
            let window = UIApplication.shared.delegate?.window
            window??.isHidden = false
            window??.addSubview(self)
        }
        
    }
    
    
    fileprivate func startTimer(){
        count = showTime
        RunLoop.main.add(self.countTimer!, forMode: .commonModes)
    }

}
